﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SVC.client;
namespace UI.Forms
{
    public partial class CardINStore : FormBase1
    {
        private cardin ca;
        private BindingList<SVC.client.CRM_Contact> contacts = new BindingList<CRM_Contact>();
        public CardINStore()
        {
            InitializeComponent();
        }
        public CardINStore(string pid)
        {
            InitializeComponent();
        }

        private void btn_import_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            号码导入 frm = new 号码导入();
            frm.FatherRefresh = import;
            frm.ShowDialog();
        }

        private void import(List<cpclass> cps,int comboid)
        {
            foreach (cpclass cp in cps)
            {
                CardIN_D d=new CardIN_D();
                d.cno=cp.cid;
                d.phoneno=cp.phoneno;
                d.pid=ca.M.pid;
                d.ComboID = comboid;
                d.quantity = 1;

                SVC.client.Combo c = my.bw.ComboByComboID_Get(comboid, my.ACID);
                d.price = c.outprice.Value;
                d.monthflag = c.monthFlag;
                if (d.monthflag)
                {
                    d.unit = "元/月";
                    d.yue = c.TCZ.Value;
                    d.amount = d.price * d.quantity;
                }
                else
                {
                    d.unit = "张";
                    d.yue = c.TCZ.Value;
                    d.amount = d.price * d.quantity;

                }
                
                ca.D.Add(d);
            }
        }

        private void CardINStore_Load(object sender, EventArgs e)
        {
            lue_opID.EditValue = my.emp_lite.EmplID;
            rue_combo.Leave += new EventHandler(rue_combo_Leave);
            rice_amount.Leave += new EventHandler(rice_amount_Leave);
            rice_price.Leave += new EventHandler(rice_price_Leave);
            rise_quantity.Leave += new EventHandler(rise_quantity_Leave);
            dateEdit1.EditValueChanged += new EventHandler(dateEdit1_EditValueChanged);
            rise_quantity.EditValueChanging += new DevExpress.XtraEditors.Controls.ChangingEventHandler(rise_quantity_EditValueChanging);
            bind();
            lue_Client.EditValueChanged += new EventHandler(lue_Client_EditValueChanged);

        }

        void lue_Client_EditValueChanged(object sender, EventArgs e)
        {
            ca.D.Clear();
            contacts.Clear();
            if (lue_Client.EditValue != null)
            {
                Guid clientid = new Guid(lue_Client.EditValue.ToString());
                bindcontact(clientid);
            }

        }

        private void bindcontact(Guid clientid)
        {
            contacts.Clear();
            foreach (var item in my.bw.CRM_Contact_Get_ByClientID(clientid, my.ACID))
            {
                contacts.Add(item);
            }
        }

        void rise_quantity_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            
        }

        private void bind()
        {
            ca = new cardin();
            ca.M = new CardIN_M();
            ca.D = new BindingList<CardIN_D>();
            ca.numbers = new BindingList<SVC.client.numberpool>();
            ca.M.balance = 0;
            ca.M.ischeck = false;
            ca.M.isfinish = false;
            ca.M.opID = my.emp_lite.EmplID;
            ca.M.Pdate = dateEdit1.DateTime;
            ca.M.pid = te_pid.Text;
            ca.M.total = 0;
            gridControl1.DataSource = ca.D;
            rue_combo.DataSource = my.bw.View_Combo_lite_List("", my.ACID);
            rue_combo.DisplayMember = "ComboName";
            rue_combo.ValueMember = "ComboID";
            dateEdit1.EditValue = DateTime.Now;
            BindingList<View_Emp_lite> emps = my.bw.View_Emp_lite_List("", my.ACID);
            BindingList<View_Client_lite> clients = my.bw.View_Client_lite_List(true, my.ACID);
            lue_Checkempid.Properties.DataSource = emps;
            lue_Checkempid.EditValue = null;
            lue_linkmen.Properties.DisplayMember = "Name";
            lue_linkmen.Properties.ValueMember = "ContactID";
            lue_linkmen.Properties.DataSource = contacts;
            lue_Client.Properties.DataSource = clients;
            lue_Client.EditValue = null;
            lue_JSempid.Properties.DataSource = emps;
            lue_JSempid.EditValue = null;
            lue_opID.Properties.DataSource = emps;
            lue_linkmen.Text = "";
            te_pid.Text = my.bw.getBillNO(my.emp_lite.shopcode, dateEdit1.DateTime, 1, my.ACID);
            te_remarks.Text = "";
            te_tel.Text = "";
        }

        void rise_quantity_Leave(object sender, EventArgs e)
        {
            string newvalue = "";
            if (gridView1.EditingValue != null)
            {
                newvalue = gridView1.EditingValue.ToString();
            }
            else
            {
                try
                {
                    newvalue = gridView1.GetFocusedRowCellValue("quantity").ToString();
                }
                catch { }

            }
            if (string.IsNullOrEmpty(newvalue) || string.IsNullOrEmpty(gridView1.GetFocusedRowCellValue("price").ToString()))
            {
                return;
            }
            int quantity = int.Parse(newvalue);
            gridView1.SetFocusedRowCellValue("amount", decimal.Parse(gridView1.GetFocusedRowCellValue("price").ToString())*quantity);
            int? comboid = null;
            try
            {
                comboid = int.Parse(gridView1.GetFocusedRowCellValue("ComboID").ToString());
            }
            catch { }
            if (comboid.HasValue)
            {
                SVC.client.Combo c = my.bw.ComboByComboID_Get(comboid.Value, my.ACID);
                if (c.monthFlag)
                {
                    gridView1.SetFocusedRowCellValue("yue", c.TCZ.Value * quantity);
                }
                else
                {
                    gridView1.SetFocusedRowCellValue("quantity", 1);
                }
                
            }
        }

        void rue_combo_Leave(object sender, EventArgs e)
        {
            string newvalue = "";
            if (gridView1.EditingValue != null)
            {
                newvalue = gridView1.EditingValue.ToString();
            }
            else
            {
                try
                {
                    newvalue = gridView1.GetFocusedRowCellValue("ComboID").ToString();
                }
                catch { }
                
            }
            if (string.IsNullOrEmpty(newvalue)) return;
            decimal quantity = decimal.Parse(gridView1.GetFocusedRowCellValue("quantity").ToString());
            decimal price = decimal.Parse(gridView1.GetFocusedRowCellValue("price").ToString());
            SVC.client.Combo c = my.bw.ComboByComboID_Get(int.Parse(newvalue), my.ACID);

            gridView1.SetFocusedRowCellValue("monthflag", c.monthFlag);


            if (quantity==0)
            {
                gridView1.SetFocusedRowCellValue("quantity", 1);
            }

            if (c.monthFlag)
            {

                gridView1.SetFocusedRowCellValue("unit", "元/月");
                gridView1.SetFocusedRowCellValue("yue", c.TCZ.Value * decimal.Parse(gridView1.GetFocusedRowCellValue("quantity").ToString()));
                if (c.inprice.HasValue)
                {
                    gridView1.SetFocusedRowCellValue("price", c.inprice.Value);
                    gridView1.SetFocusedRowCellValue("amount", c.inprice.Value * decimal.Parse(gridView1.GetFocusedRowCellValue("quantity").ToString()));
                }
               
            }
            else
            {
                gridView1.SetFocusedRowCellValue("quantity", 1);
                gridView1.SetFocusedRowCellValue("unit", "张");
                gridView1.SetFocusedRowCellValue("yue", 0);
            }
        }

        void rice_price_Leave(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("ComboID") == null)
            {
                Comm.ShowInfo("请先选择套餐！");
                return;
            }
            string newvalue = "";
            if (gridView1.EditingValue != null)
            {
                newvalue = gridView1.EditingValue.ToString();
            }
            else
            {
                newvalue = gridView1.GetFocusedRowCellValue("price").ToString();
            }
            gridView1.SetFocusedRowCellValue("amount", decimal.Parse(newvalue) * decimal.Parse(gridView1.GetFocusedRowCellValue("quantity").ToString()));

        }

        void rice_amount_Leave(object sender, EventArgs e)
        {
            if (gridView1.GetFocusedRowCellValue("ComboID") == null)
            {
                Comm.ShowInfo("请先选择套餐！");
                return;    
            }
            string newvalue = "";
            if (gridView1.EditingValue != null)
            {
                newvalue = gridView1.EditingValue.ToString();
            }
            else
            {
                newvalue = gridView1.GetFocusedRowCellValue("amount").ToString();
            }
            gridView1.SetFocusedRowCellValue("price", decimal.Parse(newvalue) / decimal.Parse(gridView1.GetFocusedRowCellValue("quantity").ToString()));
        }

        void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if (dateEdit1.EditValue==null) return;
            te_pid.Text = my.bw.getBillNO(my.emp_lite.shopcode, dateEdit1.DateTime, 1, my.ACID);
        }

        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {   
            if (e.Button==MouseButtons.Right)
            {
            Point p = this.Location;
            if (this.MdiParent!=null)
            {
                p.Offset(this.MdiParent.Location);   
            }
            p.Offset(gridControl1.Location);
            p.Offset(e.Location);
            p.Y = p.Y + 50;

                popupMenu1.ShowPopup(p);
            }
        }

        private void btn_delrow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.SelectedRowsCount > 0)
            {
                List<CardIN_D> dels=new List<CardIN_D>();
                foreach (int rh in gridView1.GetSelectedRows())
                {
                    
                   dels.Add(gridView1.GetRow(rh) as CardIN_D);
                }
                foreach (var item in dels)
                {
                    ca.D.Remove(item);
                }
            }
        }

        private void btn_updateCommp_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Combo frm = new Combo();
            frm.FatherRefresh = updateCombo;
            frm.ShowDialog();
        }

        void updateCombo(SVC.client.View_Combo_Lite combo)
        {
            rue_combo.DataSource = my.bw.View_Combo_lite_List("", my.ACID);
            if (gridView1.SelectedRowsCount > 0)
            {
                List<CardIN_D> ses = new List<CardIN_D>();
                foreach (int rh in gridView1.GetSelectedRows())
                {

                    ses.Add(gridView1.GetRow(rh) as CardIN_D);
                }
                foreach (var item in ses)
                {
                    CardIN_D cd = null;
                    try
                    {
                        cd = ca.D.Single(p => p.phoneno == item.phoneno);
                    }
                    catch (Exception )
                    {
                        Comm.ShowErorr("单据中存在两个以上号码[" + item.phoneno + "],请删除多余的行！"); return;
                    }

                    cd.ComboID=combo.ComboID;
                    cd.monthflag = combo.monthFlag;
                    if (cd.quantity==0)
                    {
                        cd.quantity=1;
                    }
                    if (combo.inprice.HasValue)
                    {
                        cd.price = combo.inprice.Value;
                    }
                    cd.yue = combo.TCZ.Value * cd.quantity;
                    cd.amount = cd.price * cd.quantity;
                    if (cd.monthflag)
                    {
                        cd.unit = "元/月";
                        
                    }
                    else
                    {
                        cd.unit = "张";
                    }
                }
            }
        }

        private void btn_OK_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (dxValidationProvider1.Validate())
            {
                if (ca.D.Count>0)
                {
                    ca.M.balance = decimal.Parse(gridColumn8.SummaryItem.SummaryValue.ToString());
                    if (lue_Checkempid.EditValue!=null)
                    {
                        ca.M.Checkempid = new Guid(lue_Checkempid.EditValue.ToString());
                    }
                    if (lue_JSempid.EditValue!=null)
                    {
                        ca.M.JSempid = new Guid(lue_JSempid.EditValue.ToString());
                    }
                    ca.M.ClientID = new Guid(lue_Client.EditValue.ToString());
                    ca.M.ischeck = false;
                    ca.M.isfinish = false;
                    ca.M.linkman = lue_linkmen.Text;
                    ca.M.opID = my.emp_lite.EmplID;
                    ca.M.Pdate = dateEdit1.DateTime;
                    ca.M.pid = te_pid.Text.Trim();
                    ca.M.Remarks = te_remarks.Text.Trim();
                    ca.M.tel = te_tel.Text;
                    ca.M.total = decimal.Parse(gridColumn8.SummaryItem.SummaryValue.ToString());


                    foreach (CardIN_D d in ca.D)
                    {
                        SVC.client.numberpool num=new SVC.client.numberpool();

                            d.pid = te_pid.Text;
                        
                            num.balance = d.yue;
                            num.ComboID = d.ComboID;

                            num.indate = ca.M.Pdate;
                            num.phone = d.phoneno;
                            num.state = 0;
                            ca.numbers.Add(num);


                    }
                    string r = my.bw.cardin_Add(ca, my.ACID);
                    if (string.IsNullOrEmpty(r))
                    {
                        bind();
                        Comm.ShowInfo("单据提交成功！");
                        
                    }
                    else
                    {
                        Comm.ShowErorr(r);
                    }
                }
                else
                {
                    Comm.ShowErorr("明细不能为空！");
                }
            }
        }

        private void lue_linkmen_EditValueChanged(object sender, EventArgs e)
        {
            if (lue_linkmen.EditValue == null) return;
            te_tel.Text = contacts.Single(p => p.ContactID == int.Parse(lue_linkmen.EditValue.ToString())).Mobile;
        }

        private void lue_linkmen_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (lue_Client.EditValue == null)
            {
                Comm.ShowAlert("请先选择一个供应商！");
                return;
            }

            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                UI.Forms.crm_contact_N frm = new crm_contact_N(new Guid(lue_Client.EditValue.ToString()));
                frm.FatherRefresh = bindlinkmen;
                frm.ShowDialog();
            }
        }

        void bindlinkmen(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return;
            }
            bindcontact(new Guid(lue_Client.EditValue.ToString()));
            lue_linkmen.Text = name;
        }

    }
}